package com.liuguoqing.framework.beans.factory.xml;

import com.liuguoqing.framework.beans.BeanDefinition;
import com.liuguoqing.framework.beans.MutablePropertyValues;
import com.liuguoqing.framework.beans.PropertyValue;
import com.liuguoqing.framework.beans.factory.support.BeanDefinitionReader;
import com.liuguoqing.framework.beans.factory.support.BeanDefinitionRegistry;
import com.liuguoqing.framework.beans.factory.support.SimpleBeanDefinitionRegistry;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author : liugq
 * @Date : 2022/7/19 16:56
 * @See : 参考类
 * @Since： JDK1.8
 * @Version : 1.0
 */
public class XmlBeanDefinitionReader implements BeanDefinitionReader {

    private BeanDefinitionRegistry registry;

    public XmlBeanDefinitionReader() {
        this.registry = new SimpleBeanDefinitionRegistry();
    }

    /**
     * 获取注册表对象
     */
    @Override
    public BeanDefinitionRegistry getRegistry() {
        return registry;
    }

    /**
     * 加载配置文件并在注册表中进行注册
     * @param configLocation
     */
    @Override
    public void loadBeanDefinitions(String configLocation) throws Exception {
        //使用dom4j解析配置文件
        SAXReader reader = new SAXReader();
        Document document = reader.read(this.getClass().getClassLoader().getResourceAsStream(configLocation));
        //获取根路径
        Element root = document.getRootElement();
        //从根路径，拿到所有的bean
        List<Element> beans = root.elements("bean");
        for (Element bean : beans) {
            //封装bean标签信息
            BeanDefinition beanDefinition = new BeanDefinition();
            beanDefinition.setId( bean.attributeValue("id") );
            beanDefinition.setClassName( bean.attributeValue("class") );
            //判断是否有property
            List<Element> list = bean.elements("property");
            //封装propertyValue信息
            MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
            list.forEach(element -> {
                PropertyValue propertyValue = new PropertyValue();
                propertyValue.setName( element.attributeValue("name") );
                propertyValue.setRef( element.attributeValue("ref") );
                propertyValue.setValue( element.attributeValue("value") );
                mutablePropertyValues.addPropertyValue(propertyValue);
            });
            beanDefinition.setPropertyValues(mutablePropertyValues);

            registry.registerBeanDefinition(beanDefinition.getId(),beanDefinition);
        }
    }
}
